import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {NzMessageService} from 'ng-zorro-antd/message';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  amount: number;
  password: string;

  on = false;
  repassword: string;
  email: string;
  text: any;
  name: any;

  constructor(private http: HttpClient, private msg: NzMessageService) {
  }

  ngOnInit(): void {

  }

  login(): void {
    const url = '/api/login/common';
    this.http.post(url, {
      amount: this.amount,
      password: this.password
    }).subscribe((resp: any) => {
      if (resp.code === 200) {
        console.log(resp);
        const data = resp.data;
        localStorage.setItem('token', data);
        window.location.href = '../';
        this.msg.success('登录成功！');
      } else {
        this.msg.error(resp.message);
      }
    });
  }

  changeOn(status: boolean): void {
    if (status === this.on) {
      if (!this.on) {
        this.login();
      } else {
        this.register();
      }
    } else {
      this.on = !this.on;
    }
  }

  sendEmail(): void {
    if (this.email === null || this.email === '' || this.email === undefined) {
      this.msg.error('请输入邮箱');
    } else if (!/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(this.email)) {
      this.msg.error('请输入正确格式的邮箱');
    } else {
      const url = '/api/user/getCode';
      this.http.post(url, {
        email: this.email
      }).subscribe((resp: any) => {
        if (resp.code === 200) {
          this.msg.success('验证码发送成功');
        } else {
          this.msg.error('服务端错误');
        }
      });
    }
  }

  register(): void {
    const url = '/api/user/register';
    this.http.post(url, {
      name: this.name,
      email: this.email,
      password: this.password,
      code: this.text
    }).subscribe((resp: any) => {
      if (resp.code === 200) {
        this.msg.success('成功，您的账号为' + resp.data);
      } else {
        this.msg.error('失败');
      }
    });
  }
}
